package com.aoxiang.zbox.common;

import com.aoxiang.zbox.config.DataSourceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class);
    Map<String, DataSource> dataSourceMap = new HashMap<>();

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSourceKey = DataSourceContextHolder.getDataSource();
        if (dataSourceKey == null) {
            return DataSourceConfig.BASE_DATASOURCE_KEY; // 默认返回 base 数据库
        }
        return dataSourceKey;
    }

    @Override
    protected DataSource determineTargetDataSource() {
        String dataSourceKey = DataSourceContextHolder.getDataSource();
        if (dataSourceKey == null) {
            dataSourceKey = DataSourceConfig.BASE_DATASOURCE_KEY;
        }
        return getOrCreateDataSource(dataSourceKey);
    }


    private synchronized DataSource getOrCreateDataSource(String dataSourceKey) {
        if (dataSourceMap.containsKey(dataSourceKey)) {
            return dataSourceMap.get(dataSourceKey);
        }

        String dbUrl = DataSourceConfig.generateDbUrl(dataSourceKey);
        DataSource newDataSource = DataSourceBuilder.create()
                .driverClassName("org.sqlite.JDBC")
                .url(dbUrl)
                .build();

        dataSourceMap.put(dataSourceKey, newDataSource);

        Map<Object, Object> targetDataSources = new HashMap<>(dataSourceMap);
        setTargetDataSources(targetDataSources);
        afterPropertiesSet(); // 通知 Spring 重新刷新数据源

        return newDataSource;
    }
}
